import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_html/flutter_html.dart';
import '../../models/notice.dart';
import '../../widgets/image_preview.dart';

class NewsPage extends StatefulWidget {
  final Notice notice;

  const NewsPage({
    super.key,
    required this.notice,
  });

  @override
  State<NewsPage> createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text(
          '通知详情',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
        backgroundColor: Colors.blue[600],
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => context.pop(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.share, color: Colors.white),
            onPressed: () {
              // TODO: 实现分享功能
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('分享功能开发中')),
              );
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头部信息
            _buildHeader(),

            // 内容区域
            _buildContent(),

            // 底部信息
            _buildFooter(),

            const SizedBox(height: 32),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha((0.05 * 255).round()),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text(
            widget.notice.title ?? '无标题',
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
              height: 1.3,
            ),
          ),

          const SizedBox(height: 16),

          // 发布信息
          Row(
            children: [
              // 发布者
              if (widget.notice.publisher != null &&
                  widget.notice.publisher!.isNotEmpty) ...[
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.person_outline,
                        size: 14,
                        color: Colors.blue[600],
                      ),
                      const SizedBox(width: 4),
                      Text(
                        widget.notice.publisher!,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.blue[600],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 12),
              ],

              // 发布时间
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.access_time,
                      size: 14,
                      color: Colors.grey[600],
                    ),
                    const SizedBox(width: 4),
                    Text(
                      _formatTime(widget.notice.publishTime),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    return Container(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 如果有图片，显示图片
          if (widget.notice.imageUrl != null &&
              widget.notice.imageUrl!.isNotEmpty)
            Container(
              margin: const EdgeInsets.only(bottom: 20),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: Image.network(
                  widget.notice.imageUrl!,
                  width: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      height: 200,
                      decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Icon(
                        Icons.image_not_supported,
                        color: Colors.grey[400],
                        size: 48,
                      ),
                    );
                  },
                  loadingBuilder: (context, child, loadingProgress) {
                    if (loadingProgress == null) return child;
                    return Container(
                      height: 200,
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Center(
                        child: CircularProgressIndicator(
                          value: loadingProgress.expectedTotalBytes != null
                              ? loadingProgress.cumulativeBytesLoaded /
                                  loadingProgress.expectedTotalBytes!
                              : null,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),

          // HTML内容渲染
          _buildHtmlContent(),
        ],
      ),
    );
  }

  Widget _buildHtmlContent() {
    final rawContent = widget.notice.content ?? '';

    // 解码HTML实体（&lt; &gt; &amp; &quot; 等）
    String decodedContent = _decodeHtmlEntities(rawContent);

    // 如果内容包含HTML标签，使用Html widget渲染
    if (decodedContent.contains('<') && decodedContent.contains('>')) {
      return Html(
        data: decodedContent,
        extensions: [
          TagExtension(
            tagsToExtend: {"img"},
            builder: (extensionContext) {
              final element = extensionContext.element;
              final src = element?.attributes['src'];
              final alt = element?.attributes['alt'] ?? '';
              
              if (src != null && src.isNotEmpty) {
                return Container(
                  margin: const EdgeInsets.symmetric(vertical: 8),
                  child: GestureDetector(
                    onTap: () {
                      // 点击图片进行全屏预览
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          fullscreenDialog: true,
                          builder: (context) => ImagePreview(
                            imagePaths: [src],
                            initialIndex: 0,
                            isNetworkImage: true,
                          ),
                        ),
                      );
                    },
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.network(
                        src,
                        fit: BoxFit.contain,
                        width: double.infinity,
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) return child;
                          return Container(
                            height: 200,
                            alignment: Alignment.center,
                            child: CircularProgressIndicator(
                              value: loadingProgress.expectedTotalBytes != null
                                  ? loadingProgress.cumulativeBytesLoaded /
                                      loadingProgress.expectedTotalBytes!
                                  : null,
                            ),
                          );
                        },
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            height: 200,
                            decoration: BoxDecoration(
                              color: Colors.grey[200],
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.broken_image,
                                  size: 48,
                                  color: Colors.grey[400],
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  alt.isNotEmpty ? alt : '图片加载失败',
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 14,
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                );
              }
              return const SizedBox.shrink();
            },
          ),
        ],
        style: {
          "body": Style(
            margin: Margins.zero,
            padding: HtmlPaddings.zero,
            fontSize: FontSize(16),
            lineHeight: const LineHeight(1.6),
            color: Colors.black87,
          ),
          "h1": Style(
            fontSize: FontSize(24),
            fontWeight: FontWeight.bold,
            margin: Margins.only(bottom: 16),
            color: Colors.black87,
          ),
          "h2": Style(
            fontSize: FontSize(20),
            fontWeight: FontWeight.bold,
            margin: Margins.only(top: 16, bottom: 12),
            color: Colors.black87,
          ),
          "h3": Style(
            fontSize: FontSize(18),
            fontWeight: FontWeight.w600,
            margin: Margins.only(top: 12, bottom: 8),
            color: Colors.black87,
          ),
          "p": Style(
            margin: Margins.only(bottom: 12),
            fontSize: FontSize(16),
            lineHeight: const LineHeight(1.6),
          ),
          "a": Style(
            color: Colors.blue[600],
            textDecoration: TextDecoration.underline,
          ),
          "strong": Style(
            fontWeight: FontWeight.bold,
          ),
          "em": Style(
            fontStyle: FontStyle.italic,
          ),
          "ul": Style(
            margin: Margins.only(bottom: 12),
            padding: HtmlPaddings.only(left: 20),
          ),
          "ol": Style(
            margin: Margins.only(bottom: 12),
            padding: HtmlPaddings.only(left: 20),
          ),
          "li": Style(
            margin: Margins.only(bottom: 4),
          ),
          "hr": Style(
            margin: Margins.symmetric(vertical: 16),
            border: Border(
              top: BorderSide(color: Colors.grey[300]!, width: 1),
            ),
          ),
          "span": Style(
              // 支持内联样式
              ),
          "div": Style(
              // 支持div容器
              ),
        },
        onLinkTap: (url, attributes, element) {
          // 处理链接点击
          if (url != null) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('链接: $url')),
            );
          }
        },
      );
    } else {
      // 如果是纯文本，使用普通Text widget
      return Text(
        decodedContent,
        style: const TextStyle(
          fontSize: 16,
          height: 1.6,
          color: Colors.black87,
        ),
      );
    }
  }

  String _decodeHtmlEntities(String htmlString) {
    // 解码常见的HTML实体
    String decoded = htmlString
        .replaceAll('&lt;', '<')
        .replaceAll('&gt;', '>')
        .replaceAll('&amp;', '&')
        .replaceAll('&quot;', '"')
        .replaceAll('&#39;', "'")
        .replaceAll('&nbsp;', ' ')
        .replaceAll('&copy;', '©')
        .replaceAll('&reg;', '®')
        .replaceAll('&trade;', '™');

    return decoded;
  }

  Widget _buildFooter() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.info_outline,
                size: 16,
                color: Colors.grey[600],
              ),
              const SizedBox(width: 8),
              Text(
                '通知信息',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          if (widget.notice.createTime != null) ...[
            _buildInfoRow('创建时间', _formatDetailTime(widget.notice.createTime!)),
            const SizedBox(height: 8),
          ],
          if (widget.notice.updateTime != null) ...[
            _buildInfoRow('更新时间', _formatDetailTime(widget.notice.updateTime!)),
          ],
        ],
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 80,
          child: Text(
            '$label:',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[700],
            ),
          ),
        ),
      ],
    );
  }

  void _showImageDialog(String imageUrl) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: Stack(
          children: [
            Center(
              child: Image.network(
                imageUrl,
                fit: BoxFit.contain,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    padding: const EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Text('图片加载失败'),
                  );
                },
              ),
            ),
            Positioned(
              top: 40,
              right: 20,
              child: IconButton(
                icon: const Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 30,
                ),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDetailTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '未知时间';

    try {
      // 如果是完整的日期时间格式 (2025-07-30T10:37:27.000+08:00)
      if (timeStr.contains('T')) {
        final dateTime = DateTime.parse(timeStr);
        return '${dateTime.year}年${dateTime.month.toString().padLeft(2, '0')}月${dateTime.day.toString().padLeft(2, '0')}日 ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
      }

      // 如果是简单的日期时间格式 (2025-07-30 10:37:27)
      if (timeStr.contains(' ')) {
        final parts = timeStr.split(' ');
        if (parts.length >= 2) {
          final datePart = parts[0];
          final timePart = parts[1];
          final dateComponents = datePart.split('-');
          if (dateComponents.length >= 3) {
            final year = dateComponents[0];
            final month = dateComponents[1];
            final day = dateComponents[2];
            final timeComponents = timePart.split(':');
            if (timeComponents.length >= 2) {
              final hour = timeComponents[0];
              final minute = timeComponents[1];
              return '${year}年${month}月${day}日 $hour:$minute';
            }
          }
        }
      }

      // 如果只是日期格式 (2025-07-30)
      if (timeStr.contains('-')) {
        final dateComponents = timeStr.split('-');
        if (dateComponents.length >= 3) {
          final year = dateComponents[0];
          final month = dateComponents[1];
          final day = dateComponents[2];
          return '${year}年${month}月${day}日';
        }
      }

      return timeStr;
    } catch (e) {
      return timeStr;
    }
  }

  String _formatTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '未知时间';

    try {
      // 如果是完整的日期时间格式
      if (timeStr.contains(' ')) {
        final parts = timeStr.split(' ');
        if (parts.length >= 2) {
          final datePart = parts[0];
          final timePart = parts[1];
          final dateComponents = datePart.split('-');
          if (dateComponents.length >= 3) {
            final month = dateComponents[1];
            final day = dateComponents[2];
            return '$month-$day ${timePart.substring(0, 5)}';
          }
        }
      }

      // 如果只是日期格式
      if (timeStr.contains('-')) {
        final dateComponents = timeStr.split('-');
        if (dateComponents.length >= 3) {
          final month = dateComponents[1];
          final day = dateComponents[2];
          return '$month-$day';
        }
      }

      return timeStr;
    } catch (e) {
      return timeStr;
    }
  }
}
